#include "spredsheet.h"

spredsheet::spredsheet(QWidget *parent) : QDialog( parent )
{
    table = new QTableWidget();

    okButton = new QPushButton("Ok");
    cancelButton = new QPushButton("Cancel");

    buttonsLayout = new QHBoxLayout();
    buttonsLayout->addStretch( 0 );
    buttonsLayout->addWidget( okButton, 0, Qt::AlignRight);
    buttonsLayout->addWidget( cancelButton, 0, Qt::AlignRight);

    mainLayout = new QVBoxLayout();
    mainLayout->addWidget( table );
    mainLayout->addLayout( buttonsLayout );

    setWindowTitle( tr("Input edit") );

    setLayout( mainLayout );

    connect(cancelButton, SIGNAL(clicked()), this, SLOT(close()) );
    connect(okButton, SIGNAL(clicked()), this, SLOT(okPressed()) );
}

void spredsheet::setSize( int n, int m )
{
    table->setColumnCount( m );
    table->setRowCount( n );
    table->adjustSize();
}

void spredsheet::clear()
{
    table->clear();
}

void spredsheet::okPressed()
{
    QVector<QVector<int> > inputTable;
    QTableWidgetItem *wi;
    bool full = true;

    inputTable.resize( table->rowCount() );
    for(int i=0; i<table->rowCount(); i++)
        inputTable[i].resize( table->columnCount() );

    bool convOK = true;
    for (int i=0; i<table->rowCount(); i++ ){
        for (int j=0; j<table->columnCount(); j++){
            wi = table->item( i, j );
            if (wi == 0) { full = false; break; } else
            {
                inputTable[i][j] = wi->text().toInt( &convOK );
                if (!convOK) break;
            }
            if (!convOK) break;
        }
        if (!full || !convOK) break;
    }

    if (!convOK){
        QMessageBox::warning( this, tr("Warning"), tr("Some cell containt not a number") );
        return;
    } else
        if (!full) {
            QMessageBox::warning( this, tr("Warning"), tr("Some cells are not filled") );
            return;
        } else {
            emit tableMade( inputTable );
            close();
        }

}
